//模块化-工程化
import Vue from 'vue'

import VueRouter from 'vue-router'
import { getToken } from '@/utils/localData.js'
Vue.use(VueRouter)

// 4. 路由映射关系(路径与组件)
// import Login from '@/views/login.vue'
// import Home from '@/views/Home.vue'
// import Index from '@/views/index.vue'
// import PostList from '@/views/Post/List.vue'
// import PostPublish from '@/views/Post/Publish.vue'
// 按需引入
// 🎃 使用jt生成箭头函数的注意：这里箭头函数简写省略了两个东西 { } 和 return
const Login = () => import('@/views/login.vue')
const Home = () => import('@/views/Home.vue')
const Index = () => import('@/views/index.vue')
const PostList = () => import('@/views/Post/List.vue')
const PostPublish = () => import('@/views/Post/Publish.vue')

const routes = [
    // { path, component, name , children,  redirect , meta  }
    { path: '/login', component: Login },
    { path: '/', redirect: '/home' },

    {
        path: '/home',
        component: Home,
        redirect: '/home/index',
        children: [
            // 🔔 注意：子路由不要写 /
            { path: 'index', component: Index },
            { path: 'post_list', component: PostList },
            //在动态路由后加个? 表示可以携带id也可以不携带id
            //有id 表示编辑文章
            // 没有id 表示发布文章
            { path: 'post_publish/:id?', component: PostPublish },
        ],
    },
]

const router = new VueRouter({
    mode: 'history',
    routes
})

// .beforeEach()  前置导航守卫
//    to      要去哪里
//    from    来自哪里
//    next    是否方向的函数
router.beforeEach((to, from, next) => {
    // 后台管理系统，只有登录页是直接放行的
    if (to.path === '/login') {
        next()
    } else {
        // 其他的页面都要检查，有 token 放行，没有就去登录页
        if (getToken()) {
            next()
        } else {
            // next({ path: '/login' })
            next('/login')
        }
    }
})

export default router